import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import '../models/ssh_connection.dart';
import '../services/database_service.dart';

class ConnectionEditScreen extends StatefulWidget {
  final SSHConnection? connection;

  const ConnectionEditScreen({super.key, this.connection});

  @override
  State<ConnectionEditScreen> createState() => _ConnectionEditScreenState();
}

class _ConnectionEditScreenState extends State<ConnectionEditScreen> {
  final _formKey = GlobalKey<FormState>();
  late final _uuid = const Uuid();

  late String _name;
  late String _host;
  late int _port;
  late String _username;
  String? _password;
  String? _privateKeyPath;
  String? _passphrase;

  final _nameController = TextEditingController();
  final _hostController = TextEditingController();
  final _portController = TextEditingController();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _privateKeyPathController = TextEditingController();
  final _passphraseController = TextEditingController();

  @override
  void initState() {
    super.initState();
    
    final connection = widget.connection;
    if (connection != null) {
      _name = connection.name;
      _host = connection.host;
      _port = connection.port;
      _username = connection.username;
      _password = connection.password;
      _privateKeyPath = connection.privateKeyPath;
      _passphrase = connection.passphrase;

      _nameController.text = _name;
      _hostController.text = _host;
      _portController.text = _port.toString();
      _usernameController.text = _username;
      _passwordController.text = _password ?? '';
      _privateKeyPathController.text = _privateKeyPath ?? '';
      _passphraseController.text = _passphrase ?? '';
    } else {
      _name = '';
      _host = '';
      _port = 22;
      _username = '';
      _passwordController.text = '';
      _portController.text = '22';
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _hostController.dispose();
    _portController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _privateKeyPathController.dispose();
    _passphraseController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.connection == null ? '添加连接' : '编辑连接'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  labelText: '连接名称',
                  hintText: '例如: 生产服务器',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入连接名称';
                  }
                  return null;
                },
                onChanged: (value) => _name = value,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _hostController,
                decoration: const InputDecoration(
                  labelText: '主机地址',
                  hintText: '例如: 192.168.1.100',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入主机地址';
                  }
                  return null;
                },
                onChanged: (value) => _host = value,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _portController,
                decoration: const InputDecoration(
                  labelText: '端口',
                  hintText: '22',
                ),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入端口号';
                  }
                  final port = int.tryParse(value);
                  if (port == null || port <= 0 || port > 65535) {
                    return '请输入有效的端口号';
                  }
                  return null;
                },
                onChanged: (value) => _port = int.tryParse(value) ?? 22,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _usernameController,
                decoration: const InputDecoration(
                  labelText: '用户名',
                  hintText: '例如: root',
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  return null;
                },
                onChanged: (value) => _username = value,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _passwordController,
                decoration: const InputDecoration(
                  labelText: '密码',
                  hintText: '留空使用密钥认证',
                ),
                obscureText: true,
                onChanged: (value) => _password = value.isEmpty ? null : value,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _privateKeyPathController,
                decoration: InputDecoration(
                  labelText: '私钥文件路径',
                  hintText: '例如: ~/.ssh/id_rsa',
                  suffixIcon: IconButton(
                    icon: const Icon(Icons.folder_open),
                    onPressed: _pickPrivateKey,
                  ),
                ),
                onChanged: (value) => _privateKeyPath = value.isEmpty ? null : value,
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _passphraseController,
                decoration: const InputDecoration(
                  labelText: '私钥密码',
                  hintText: '如果私钥有密码',
                ),
                obscureText: true,
                onChanged: (value) => _passphrase = value.isEmpty ? null : value,
              ),
              const SizedBox(height: 32),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _saveConnection,
                  child: const Text('保存连接'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _pickPrivateKey() async {
    // 在实际应用中，这里应该使用文件选择器
    // 为了简化，这里使用文本输入
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('请在文本框中输入私钥文件路径'),
      ),
    );
  }

  void _saveConnection() async {
    if (_formKey.currentState!.validate()) {
      final connection = SSHConnection(
        id: widget.connection?.id ?? _uuid.v4(),
        name: _nameController.text,
        host: _hostController.text,
        port: int.parse(_portController.text),
        username: _usernameController.text,
        password: _passwordController.text.isEmpty ? null : _passwordController.text,
        privateKeyPath: _privateKeyPathController.text.isEmpty ? null : _privateKeyPathController.text,
        passphrase: _passphraseController.text.isEmpty ? null : _passphraseController.text,
      );

      final databaseService = context.read<DatabaseService>();
      await databaseService.saveConnection(connection);

      if (mounted) {
        Navigator.pop(context, true);
      }
    }
  }
}